<?php

namespace App\Services;

use App\Common\Libs\Ali\Oss;
use App\Common\Libs\ArrayHelper;
use App\Common\Libs\Dispatch\Console;
use App\Common\Libs\Dispatch\Queue;
use App\Common\Libs\IdBuilder;
use App\Common\Libs\Json;
use App\Console\Commands\Controller\MessageCountCommand;
use App\Consts\GlobalAnnounceConst;
use App\Consts\GlobalConsoleConst;
use App\Consts\GlobalConst;
use App\Consts\GlobalMessageConst;
use App\Consts\GlobalMessageTemplateConst;
use App\Consts\GlobalNoteConst;
use App\Consts\GlobalQueueConst;
use App\Consts\GlobalReplyConst;
use App\Consts\GlobalUploadConst;
use App\Events\Message\ReadAnnounceEvent;
use App\Exceptions\Error;
use App\Jobs\Controller\MessageJob;
use App\Models\Field\ArticleField;
use App\Models\Field\CommentField;
use App\Models\Field\NoteField;
use App\Models\Field\ReplyField;
use App\Models\Field\UserField;
use App\Models\IndexArticle;
use App\Models\Select\UserSelect;
use App\Models\SysArticle;
use App\Models\SysComment;
use App\Models\SysDynamic;
use App\Models\SysNote;
use App\Models\SysReply;
use App\Models\UserAnnounce;
use App\Models\UserMessageCommentSend;
use App\Models\UserMessageLikeReceive;
use App\Models\UserMessageLikeSend;

/**
 * @package App\Services
 * @see MessageService
 */
class MessageService extends BaseService
{

    /** @var $_repository */
    public $_repository;

    /**
     * MessageService constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->_repository = repository()->MessageRepository;
    }

    public function createCommentMessage($loadData)
    {
        $staticMessageInfo = $loadData['static_message'];
        unset($loadData['static_message']);

        $senderMessageId = IdBuilder::getUniqueID();
        $senderMessage = repository()->MessageRepository->createSenderMessage(ArrayHelper::merge($loadData, [
            'message_id' => $senderMessageId
        ]));
        // 静态化发出的评论
        $sendStaticMessageInfo = ArrayHelper::merge([
            'id' => $senderMessageId,
            'created_at' => $senderMessage['created_at']
        ], $staticMessageInfo);

        Oss::getInstance(GlobalUploadConst::OBJECT_COMMENT_MSG_SEND . $loadData['sender_id'] . '/')
            ->uploadTarget($sendStaticMessageInfo);

        if ($loadData['sender_id'] != $loadData['receive_id']) {
            $receiveMessageId = IdBuilder::getUniqueID();
            $receiveMessage = repository()->MessageRepository->createReceiveMessage(ArrayHelper::merge($loadData, [
                'message_id' => $receiveMessageId
            ]));

            $msgCount = repository()->MessageCountRepository->getUserMsgCountByUserIdAndMsgType($loadData['receive_id'], GlobalMessageConst::COUNT_TYPE_COMMENT);
            if (!$msgCount) {
                repository()->MessageCountRepository->createMessageCount([
                    'user_id' => $loadData['receive_id'],
                    'message_type' => GlobalMessageConst::COUNT_TYPE_COMMENT,
                    'count' => 1,
                ]);
            } else {
                $count = ++$msgCount->count;
                repository()->MessageCountRepository->updateMessageCount($msgCount, [
                    'count' => $count,
                ]);
            }

            // 静态化收到的评论
            $receiveStaticMessageInfo = ArrayHelper::merge([
                'id' => $receiveMessageId,
                'created_at' => $receiveMessage['created_at']
            ], $staticMessageInfo);
            Oss::getInstance(GlobalUploadConst::OBJECT_COMMENT_MSG_RECEIVE . $loadData['receive_id'] . '/')
                ->uploadTarget($receiveStaticMessageInfo);
        }

        return true;
    }

    /**
     * 获取评论消息的静态化内容
     * @param $comment
     * @return array|bool
     */
    public function getLoadDataByComment($comment)
    {
        $receiveUserId = service()->CommentService->getTargetUserId($comment);
        if (!$receiveUserId) {
            return false;
        }

        return [
            'sender_id' => $comment['user_id'],
            'receive_id' => $receiveUserId,
            'comment_id' => $comment['comment_id'],
            'target_id' => $comment['target_id'],
            'target_user_id' => $receiveUserId,
            'target_type' => $comment['target_type'],
            'note_type' => $comment->note_type,
            'type' => GlobalMessageConst::MSG_TYPE_COMMENT,
            'static_message' => $this->getCommentStaticMessageData($comment)
        ];
    }

    /**
     * 获取回复消息的静态化内容
     * @param $reply
     * @return array|bool
     */
    public function getLoadDataByReply($reply)
    {
        $toReply = repository()->ReplyRepository->getReplyByReplyId($reply['to_reply_id']);
        return [
            'sender_id' => $reply['user_id'],
            'receive_id' => $reply['to_user_id'],
            'comment_id' => $reply['comment_id'],
            'reply_id' => $reply['reply_id'],
            'to_user_id' => $toReply->to_user_id ?? '',
            'target_id' => $reply['target_id'],
            'target_type' => $reply['target_type'],
            'type' => GlobalMessageConst::MSG_TYPE_REPLY,
            'static_message' => $this->getReplyStaticMessageData($reply)
        ];
    }

    /**
     * 获取评论消息的静态化内容
     * @param SysComment $comment
     * @return array
     */
    public function getCommentStaticMessageData($comment)
    {
        $target = [];

        /**
         * @var SysNote $note
         * @var SysArticle $article
         * @var SysDynamic $dynamic
         */
        if ($comment['target_type'] == GlobalConst::TARGET_TYPE_NOTE) {
            $note = $comment->note ?? null;
            if ($note) {
                $article = $note->article;
                $target = [
                    'target_type' => GlobalConst::TARGET_TYPE_NOTE,
                    'note' => ArrayHelper::merge($note->commonFormat(NoteField::MESSAGE_STATIC), [
                        'content' => $note->content ?? '',
                        'article' => $article->commonFormat(ArticleField::MESSAGE_STATIC),
                    ]),
                ];
            }
        }

        return [
            'main' => ArrayHelper::merge($comment->commonFormat(CommentField::MESSAGE_STATIC), [
                'target_type' => GlobalConst::TARGET_TYPE_COMMENT,
            ]),
            'child' => [],
            'target' => $target
        ];
    }

    /**
     * 获取回复静态化内容
     * @param SysReply $reply
     * @return array
     */
    public function getReplyStaticMessageData($reply)
    {
        $target = [];

        /**
         * @var SysComment $comment
         */
        if ($reply['type'] == GlobalReplyConst::REPLY_TYPE_COMMENT) {
            $comment = $reply->comment;
            $child = ArrayHelper::merge($comment->commonFormat(CommentField::MESSAGE_STATIC), [
                'target_type' => GlobalConst::TARGET_TYPE_COMMENT,
                'user' => $reply->user->commonFormat(UserField::COMMENT),
                'to_user' => $reply->toUser->commonFormat(UserField::COMMENT)
            ]);
        } else {
            $toReply = $reply->toReply;
            $child = ArrayHelper::merge($toReply->commonFormat(ReplyField::MESSAGE_STATIC), [
                'target_type' => GlobalConst::TARGET_TYPE_REPLY,
                'user' => $reply->user->commonFormat(UserField::COMMENT),
                'to_user' => $reply->toUser->commonFormat(UserField::COMMENT)
            ]);
        }
        if ($reply['target_type'] == GlobalConst::TARGET_TYPE_NOTE) {
            $note = $reply->note ?? null;
            if ($note) {
                $target = [
                    'target_type' => GlobalConst::TARGET_TYPE_NOTE,
                    'note' => ArrayHelper::merge($note->commonFormat(NoteField::MESSAGE_STATIC), [
                        'content' => $note->content ?? '',
                        'article' => !$note->article ? [] : $note->article->commonFormat(ArticleField::MESSAGE_STATIC),
                    ]),
                ];
            }
        }

        return [
            'main' => ArrayHelper::merge($reply->commonFormat(ReplyField::MESSAGE_STATIC), [
                'target_type' => GlobalConst::TARGET_TYPE_REPLY,
            ]),
            'child' => $child,
            'target' => $target
        ];
    }

    /**
     * 获取点赞静态化内容
     * @param UserMessageLikeSend|UserMessageLikeReceive $like
     * @return array
     */
    public function getLikeStaticMessageData($like)
    {
        $result = [];
        /**
         * @var SysNote $note
         * @var SysArticle $article
         * @var SysComment $comment
         * @var SysReply $reply
         * @var SysDynamic $dynamic
         */
        if ($like['target_type'] == GlobalConst::TARGET_TYPE_NOTE && !empty($like->note)) {
            $note = $like->note;
            $result = [
                'main' => [
                    'target_type' => GlobalConst::TARGET_TYPE_NOTE
                ],
                'child' => [],
                'target' => [
                    'target_type' => GlobalConst::TARGET_TYPE_NOTE,
                    'note' => ArrayHelper::merge($note->commonFormat(NoteField::MESSAGE_STATIC), [
                        'content' => $note->content ?? '',
                        'article' => $note->article->commonFormat(ArticleField::MESSAGE_STATIC)
                    ])
                ]
            ];
        }
        if ($like['target_type'] == GlobalConst::TARGET_TYPE_COMMENT && !empty($like->comment)) {
            $comment = $like->comment;
            if ($comment->target_type == GlobalConst::TARGET_TYPE_NOTE) {
                $note = $comment->note;
                $result = [
                    'main' => ArrayHelper::merge($comment->commonFormat(CommentField::MESSAGE_STATIC), [
                        'target_type' => GlobalConst::TARGET_TYPE_COMMENT,
                    ]),
                    'child' => ArrayHelper::merge($comment->commonFormat(CommentField::MESSAGE_STATIC), [
                        'target_type' => GlobalConst::TARGET_TYPE_COMMENT,
                    ]),
                    'target' => [
                        'target_type' => GlobalConst::TARGET_TYPE_NOTE,
                        'note' => ArrayHelper::merge($note->commonFormat(NoteField::MESSAGE_STATIC), [
                            'content' => $note->content ?? '',
                            'article' => $note->article->commonFormat(ArticleField::MESSAGE_STATIC)
                        ])
                    ]
                ];
            }
        }
        if ($like['target_type'] == GlobalConst::TARGET_TYPE_REPLY && !empty($like->reply)) {
            $reply = $like->reply;
            $comment = $reply->comment;
            $note = $comment->note;
            if ($comment->target_type == GlobalConst::TARGET_TYPE_NOTE) {
                $result = [
                    'main' => ArrayHelper::merge($reply->commonFormat(ReplyField::MESSAGE_STATIC), [
                        'target_type' => GlobalConst::TARGET_TYPE_REPLY,
                    ]),
                    'child' => ArrayHelper::merge($reply->commonFormat(ReplyField::MESSAGE_STATIC), [
                        'target_type' => GlobalConst::TARGET_TYPE_REPLY,
                        'user' => $reply->user->commonFormat(UserField::COMMENT),
                        'to_user' => $reply->toUser->commonFormat(UserField::COMMENT)
                    ]),
                    'target' => [
                        'target_type' => GlobalConst::TARGET_TYPE_NOTE,
                        'note' => ArrayHelper::merge($note->commonFormat(NoteField::MESSAGE_STATIC), [
                            'content' => $note->content ?? '',
                            'article' => $note->article->commonFormat(ArticleField::MESSAGE_STATIC)
                        ])
                    ]
                ];
            }
        }

        return $result;
    }

    /**
     * @param $searchParams
     * @param $userId
     * @return array|mixed
     */
    public function getUserAnnounce($searchParams)
    {
        $dataProvider = $this->_repository->getUserAnnounce($searchParams);
        $pagination = $this->getPagination();
        $userAnnounces = $dataProvider->get();

        if (empty($userAnnounces)) {
            return $this->searchList['more'];
        }

        $sysAnnounces = $this->_repository->getSysAnnounce(ArrayHelper::getColumn($userAnnounces, 'announce_id'));

        $list = [];
        $sysAnnounces = collect($sysAnnounces->toArray());
        // 格式化未使用模板的系统公告
        $notUseAry = $sysAnnounces->where('is_use_template', GlobalAnnounceConst::IS_NOT_USE_TEMPLATE);
        if ($notUseAry->isNotEmpty()) {
            foreach ($notUseAry as $normalSysAnnounce) {
                $announce = $normalSysAnnounce;
                $list[] = array_merge($announce, [
                    'content' => [
                        'html' => $announce['content'],
                        'operating' => ''
                    ],
                ]);
            }
        }

        // 格式化使用模板的系统公告
        $usedAry = $sysAnnounces->where('is_use_template', GlobalAnnounceConst::IS_USE_TEMPLATE);
        if ($usedAry->isNotEmpty()) {
            $templateSysAnnounces = $usedAry;
            $templates = $this->_repository->getSysMessageTpl($templateSysAnnounces->pluck('template_id')->unique());
            $templates = $templates->keyBy('id');
            foreach ($templateSysAnnounces as $templateSysAnnounce) {
                $templateSysAnnounce = (object)$templateSysAnnounce;
                if (isset($templates[$templateSysAnnounce->template_id])) {
                    $list[] = [
                        'id' => $templateSysAnnounce->id,
                        'title' => $templates[$templateSysAnnounce->template_id]->title,
                        'content' => [
                            'html' => $this->getUserAnnounceContent(
                                $templates[$templateSysAnnounce->template_id]->content,
                                explode(',', $templateSysAnnounce->template_content_params),
                                $templates[$templateSysAnnounce->template_id]->sign
                            ),
                            'operating' => '',
                        ],
                        'created_at' => $templateSysAnnounce->created_at,
                    ];
                }
            }
        }
        $list = ArrayHelper::multiSort($list, 'created_at', SORT_DESC);

        ReadAnnounceEvent::dispatch([
            'user_id' => $searchParams['user_id']
        ]);

        return self::outputMoreList($dataProvider, $pagination, $list);
    }

    /**
     * @param $content
     * @param $params
     * @return mixed
     */
    public function getUserAnnounceContent($content, $params, $sign)
    {
        preg_match_all('/{\$(.*?)}/', $content, $match);
        foreach ($match[1] as $index => $paramsName) {
            if ($sign == GlobalMessageTemplateConst::TEMPLATE_SOLVE_FEEDBACK && strlen($params[$index]) > 20) {
                $replace = mb_substr($params[$index], 0, 20) . '...';
            } else {
                $replace = $params[$index];
            }

            $content = str_replace($match[0][$index], $replace, $content);
        }

        return $content;
    }

    /**
     * 清空用户未读消息
     * @param $userId
     * @param int $messageType
     * @return bool|mixed
     */
    public function clearUnread($userId, $messageType = GlobalMessageConst::COUNT_TYPE_ALL)
    {
        if (empty($userId)) {
            return false;
        }

        // 命令行执行 - 清空未读消息
        Console::getInstance(MessageCountCommand::class)
            ->push([
                'user_id' => $userId,
                'message_type' => $messageType,
            ], GlobalConsoleConst::MESSAGE_COUNT_CLEAN);

        return true;
    }

    /**
     * 我收到的评论
     * @param $searchParams
     * @param $userId
     * @return array|mixed
     */
    public function getUserReceiveCommentList($searchParams, $userId)
    {
        $dataProvider = $this->_repository->getUserReceiveCommentList($searchParams);
        $pagination = $this->getPagination();
        $messages = $dataProvider->get();

        // 格式化结构，保证前端不改
        $list = $this->formatCommentMsg($messages);

        // 命令行执行 - 清空评论消息
        $result = $this->clearUnread($userId, GlobalMessageConst::COUNT_TYPE_COMMENT);
        if (false === $result) {
            return Error::handle();
        }

        return self::outputMoreList($dataProvider, $pagination, $list);
    }

    /**
     * 我发出的评论
     * @param $searchParams
     * @param $userId
     * @return \Illuminate\Http\JsonResponse|array
     */
    public function getUserSendCommentList($searchParams, $userId)
    {
        $dataProvider = $this->_repository->getUserSendCommentList($searchParams);
        $pagination = $this->getPagination();
        $messages = $dataProvider->get();

        // 格式化结构，保证前端不改
        $list = $this->formatCommentMsg($messages, 'send');

        // 命令行执行 - 清空评论消息
        $result = $this->clearUnread($userId, GlobalMessageConst::COUNT_TYPE_COMMENT);
        if (false === $result) {
            return Error::handle();
        }

        return self::outputMoreList($dataProvider, $pagination, $list);
    }

    private function formatCommentMsg($messages, $msgType = 'receive')
    {
        // 用户
        $userIdArr = ArrayHelper::getColumn($messages, 'sender_id');
        $userIdArr = ArrayHelper::merge(ArrayHelper::getColumn($messages, 'receive_id'), $userIdArr);
        $userIdArr = ArrayHelper::merge(ArrayHelper::getColumn($messages, 'to_user_id'), $userIdArr);
        $userIdArr = ArrayHelper::merge(ArrayHelper::getColumn($messages, 'target_user_id'), $userIdArr);
        $users = repository()->UserRepository
            ->getUserByUserIdArr($userIdArr, UserSelect::MESSAGE);
        $users = ArrayHelper::index($users, 'user_id');

        $list = [];
        foreach ($messages as $message) {
            if ($msgType == 'send') {
                $messageJson = Oss::getInstance(GlobalUploadConst::OBJECT_COMMENT_MSG_SEND . $message->sender_id . '/')
                    ->getObject($message->message_id . '.json');
            } elseif ($msgType == 'receive') {
                $messageJson = Oss::getInstance(GlobalUploadConst::OBJECT_COMMENT_MSG_RECEIVE . $message->receive_id . '/')
                    ->getObject($message->message_id . '.json');
            }
            if ($messageJson) {
                // 【V2.0.3】以下代码为格式化消息，保证前端不改
                $messageInfo = Json::decode($messageJson, true);
                $messageInfo['main']['user'] = isset($users[$message->sender_id]) ? $users[$message->sender_id]->commonFormat() : (object)[];
                if ($messageInfo['target']['target_type'] == GlobalConst::TARGET_TYPE_NOTE) {
                    if ($messageInfo['target']['note']['type'] != GlobalNoteConst::TYPE_ESSAY_NOTE) {
                        $articleId = $messageInfo['target']['note']['article']['id'];
                        $messageInfo['target']['note']['article']['is_deleted'] = IndexArticle::getInstance()
                            ->select(['is_deleted'])
                            ->where('article_id', $articleId)
                            ->value('is_deleted');
                    }
                    $messageInfo['target'] = ArrayHelper::merge($messageInfo['target']['note'], [
                        'target_type' => $messageInfo['target']['target_type']
                    ]);
                } elseif ($messageInfo['target']['target_type'] == GlobalConst::TARGET_TYPE_DYNAMIC) {
                    if (array_key_exists('article', $messageInfo['target']['dynamic'])) {
                        $articleId = $messageInfo['target']['dynamic']['article']['id'];
                        $messageInfo['target']['dynamic']['article']['is_deleted'] = IndexArticle::getInstance()
                            ->select(['is_deleted'])
                            ->where('article_id', $articleId)
                            ->value('is_deleted');
                        $messageInfo['target'] = ArrayHelper::merge($messageInfo['target']['dynamic']['article'], [
                            'target_type' => $messageInfo['target']['target_type']
                        ]);
                    } elseif (array_key_exists('note', $messageInfo['target']['dynamic'])) {
                        if ($messageInfo['target']['dynamic']['note']['type'] != GlobalNoteConst::TYPE_ESSAY_NOTE) {
                            $articleId = $messageInfo['target']['dynamic']['note']['article']['id'];
                            $messageInfo['target']['dynamic']['note']['article']['is_deleted'] = IndexArticle::getInstance()
                                ->select(['is_deleted'])
                                ->where('article_id', $articleId)
                                ->value('is_deleted');
                        }
                        $messageInfo['target'] = ArrayHelper::merge($messageInfo['target']['dynamic']['note'], [
                            'target_type' => GlobalConst::TARGET_TYPE_NOTE
                        ]);
                    }
                }
                if ($messageInfo['main']['target_type'] == GlobalConst::TARGET_TYPE_REPLY) {
                    $messageInfo['child']['user'] = $users[$message['receive_id']]->commonFormat();
                    if ($messageInfo['child']['target_type'] == GlobalConst::TARGET_TYPE_REPLY) {
                        if (!empty($message['to_user_id'])) {
                            $messageInfo['child']['to_user'] = $users[$message['to_user_id']]->commonFormat();
                        }
                    }
                }
                $list[] = $messageInfo;
            }
        }
        return $list;
    }

    /**
     * 我收到的赞
     * @param $searchParams
     * @param $userId
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function getUserReceiveLikeList($searchParams, $userId)
    {
        $searchParams['target_type'] = [GlobalConst::TARGET_TYPE_NOTE, GlobalConst::TARGET_TYPE_DYNAMIC];
        $dataProvider = $this->_repository->getUserReceiveLikeList($searchParams);
        $pagination = $this->getPagination();
        $messages = $dataProvider->getModels();
        // 用户
        $userIdArr = ArrayHelper::getColumn($messages, 'sender_id');
        $userIdArr = ArrayHelper::merge(ArrayHelper::getColumn($messages, 'receive_id'), $userIdArr);
        $userIdArr = ArrayHelper::merge(ArrayHelper::getColumn($messages, 'to_user_id'), $userIdArr);
        $userIdArr = ArrayHelper::merge(ArrayHelper::getColumn($messages, 'target_user_id'), $userIdArr);
        $users = repository()->UserRepository
            ->getUserByUserIdArr($userIdArr, UserSelect::MESSAGE);
        $users = ArrayHelper::index($users, 'user_id');

        $list = [];
        /**
         * @var UserMessageCommentSend $message
         */
        foreach ($messages as $message) {
            $messageJson = Oss::getInstance(GlobalUploadConst::OBJECT_LIKE_MSG_RECEIVE . $message->receive_id . '/')
                ->getObject($message->message_id . '.json');
            if ($messageJson) {
                $messageInfo = Json::decode($messageJson, true);
                $messageInfo['main']['user'] = isset($users[$message->sender_id]) ? $users[$message->sender_id]->commonFormat() : (object)[];
                $messageInfo['main']['to_user'] = isset($users[$message->sender_id]) ? $users[$message->sender_id]->commonFormat() : (object)[];
                if ($messageInfo['target']['target_type'] == GlobalConst::TARGET_TYPE_NOTE) {
                    if ($messageInfo['target']['note']['type'] != GlobalNoteConst::TYPE_ESSAY_NOTE) {
                        $articleId = $messageInfo['target']['note']['article']['id'];
                        $messageInfo['target']['note']['article']['is_deleted'] = IndexArticle::getInstance()
                            ->select(['is_deleted'])
                            ->where('article_id', $articleId)
                            ->value('is_deleted');
                    }
                    $messageInfo['child'] = ArrayHelper::merge($messageInfo['target']['note'], [
                        'target_type' => $messageInfo['target']['target_type']
                    ]);
                } elseif ($messageInfo['target']['target_type'] == GlobalConst::TARGET_TYPE_DYNAMIC) {
                    if (array_key_exists('article', $messageInfo['target']['dynamic'])) {
                        $articleId = $messageInfo['target']['dynamic']['article']['id'];
                        $messageInfo['target']['dynamic']['article']['is_deleted'] = IndexArticle::getInstance()
                            ->select(['is_deleted'])
                            ->where('article_id', $articleId)
                            ->value('is_deleted');
                        $messageInfo['child'] = ArrayHelper::merge($messageInfo['target']['dynamic']['article'], [
                            'target_type' => $messageInfo['target']['target_type']
                        ]);
                    } elseif (array_key_exists('note', $messageInfo['target']['dynamic'])) {
                        if ($messageInfo['target']['dynamic']['note']['type'] != GlobalNoteConst::TYPE_ESSAY_NOTE) {
                            $articleId = $messageInfo['target']['dynamic']['note']['article']['id'];
                            $messageInfo['target']['dynamic']['note']['article']['is_deleted'] = IndexArticle::getInstance()
                                ->select(['is_deleted'])
                                ->where('article_id', $articleId)
                                ->value('is_deleted');
                        }
                        $messageInfo['child'] = ArrayHelper::merge($messageInfo['target']['dynamic']['note'], [
                            'target_type' => GlobalConst::TARGET_TYPE_NOTE
                        ]);
                    }
                }
                if ($messageInfo['main']['target_type'] == GlobalConst::TARGET_TYPE_REPLY) {
                    $messageInfo['child']['user'] = $users[$message['receive_id']]->commonFormat();
                    if ($messageInfo['child']['target_type'] == GlobalConst::TARGET_TYPE_REPLY) {
                        $messageInfo['child']['to_user'] = $users[$message['to_user_id']]->commonFormat();
                    }
                }

                unset($messageInfo['target']);
                $list[] = $messageInfo;
            }
        }

        // 命令行执行 - 清空点赞消息
        $result = $this->clearUnread($userId, GlobalMessageConst::COUNT_TYPE_LIKE);
        if (false === $result) {
            return Error::handle();
        }

        return self::outputMoreList($dataProvider, $pagination, $list);
    }

    public function getUserUnread($userId)
    {
        if (!$userId) {
            return ['comment' => 0, 'like' => 0, 'announce' => 0];
        }

        $list = $this->_repository->getUserUnread($userId);
        if (!$list) {
            return ['comment' => 0, 'like' => 0, 'announce' => 0];
        }
        $data = [];
        foreach ($list as $model) {
            $data[GlobalMessageConst::$messageType[$model->message_type]] = $model->count;
        }
        $unreadAnnounce = (int)UserAnnounce::getInstance($userId)
            ->select(['id'])
            ->whereNotNull('announce_user_id')
            ->where('user_id', $userId)
            ->where('is_read', GlobalMessageConst::IS_NOT_READ)
            ->count();
        return [
            'comment' => array_key_exists('comment', $data) ? $data['comment'] : 0,
            'like' => array_key_exists('like', $data) ? $data['like'] : 0,
            'announce' => $unreadAnnounce,
        ];
    }

    /**
     * 修改用户未读消息数
     * @param array $data ['user_id' => '', 'message_type' => '']
     * @return \Illuminate\Foundation\Bus\PendingDispatch
     */
    public function changeUnreadCount($data)
    {
        return Queue::getInstance(MessageJob::class)
            ->push($data, GlobalQueueConst::MESSAGE_CHANGE_UNREAD_COUNT);
    }

    /**
     * 保存和静态化评论/回复消息
     * @param $data
     * @return \Illuminate\Foundation\Bus\PendingDispatch
     */
    public function saveAndStaticCommentMessage($data)
    {
        return Queue::getInstance(MessageJob::class)
            ->push($data, GlobalQueueConst::MESSAGE_STATIC_COMMENT);
    }

    /**
     * 静态化【我收到的点赞】消息
     * @param $data
     * @return \Illuminate\Foundation\Bus\PendingDispatch
     */
    public function staticLikeMessage($data)
    {
        return Queue::getInstance(MessageJob::class)
            ->push($data, GlobalQueueConst::MESSAGE_STATIC_LIKE);
    }
}
